package com.servlet;

import com.entity.Users;
import com.service.AdminService;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebServlet("/deleteAdmin")
public class DeleteAdminServlet extends HttpServlet {
    AdminService adminService;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.adminService=new AdminService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String useridStr = req.getParameter("userid");
        int userid = Integer.parseInt(useridStr);
        try {
            if(ifExistsById(req,userid)){
                System.out.println("if");
                req.getRequestDispatcher("/adminSearch").forward(req,resp);
            }else {
                boolean b=false;
                try {
                    b = adminService.deleteUserById(userid);
                    if(!b){
                        String error="删除不成功，请重新选择";
                        req.setAttribute("eerror",error);
                    }
                    req.getRequestDispatcher("/adminSearch").forward(req,resp);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private boolean ifExistsById(HttpServletRequest req, int userid) throws Exception {
        String username =(String) req.getSession().getAttribute("username");
        System.out.println("username:"+username);
        Users users = adminService.selectUserById(userid);
        System.out.println("users.getUserid():"+users.getUserid());
        if(username.equals(users.getUsername())){
            return true;
        }else {
            return false;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
